package com.zqs.compareface.utils.impl;

import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.bytedeco.javacv.OpenCVFrameConverter;
import org.opencv.core.Mat;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Objects;

/**
 * @program: FaceCompar
 * @description:
 * @author: ZQS
 * @create: 2021-08-07 20:29
 */
public class ImageToBase64Util {
    private static String base64image;
    private static String strNetImageToBase64;
    /**
     * 本地图片转换为base64code
     * @param imagePath
     */
    public static String convertBase64(String imagePath) {
        byte[] data = null;
        try {
            InputStream in = new FileInputStream(imagePath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
       return encoder.encode(Objects.requireNonNull(data));
    }

    /**
     * URL网络图片转换为base64code
     * @param imageurl
     * @return base64code
     */
    public static String convertBase64(URL imageurl){
        final ByteArrayOutputStream data = new ByteArrayOutputStream();
        String encodedImage = null;
        try {
            // 创建URL
//            URL url = new URL(netImagePath);
            final byte[] by = new byte[1024];
            // 创建链接
            final HttpURLConnection conn = (HttpURLConnection) imageurl.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            InputStream is = conn.getInputStream();
            // 将内容读取内存中
            int len = -1;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
            // 对字节数组Base64编码
            BASE64Encoder encoder = new BASE64Encoder();
            encodedImage  = encoder.encode(data.toByteArray());
            // 关闭流
            is.close();
            return encodedImage;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return encodedImage;
    }

    /**
     * BufferedImage 转换为base64code
     * @param bufferedImage
     * @return base64code
     */
    public static String convertBase64(BufferedImage bufferedImage) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(bufferedImage,"jpg", byteArrayOutputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(byteArrayOutputStream.toByteArray());

    }

    /**
     * Mat类型转为base64code
     * @param mat
     * @return
     */
    public static String convertToBase64(Mat mat){
        OpenCVFrameConverter.ToOrgOpenCvCoreMat converter = new OpenCVFrameConverter.ToOrgOpenCvCoreMat();
        Frame frame = converter.convert(mat);
        BufferedImage bufferedImage = new Java2DFrameConverter().getBufferedImage(frame);
        return ImageToBase64Util.convertBase64(bufferedImage);
    }

    /**
     * Mat类型转为BufferedImage
     * @param  matrix
     * @return BufferedImage
     */
    public static BufferedImage convertToBufferedImage(Mat matrix) {
        int cols = matrix.cols();
        int rows = matrix.rows();
        int elemSize = (int) matrix.elemSize();
        byte[] data = new byte[cols * rows * elemSize];
        int type;
        matrix.get(0, 0, data);
        switch (matrix.channels()) {
            case 1:
                type = BufferedImage.TYPE_BYTE_GRAY;
                break;
            case 3:
                type = BufferedImage.TYPE_3BYTE_BGR;
                // bgr to rgb
                byte b;
                for (int i = 0; i < data.length; i = i + 3) {
                    b = data[i];
                    data[i] = data[i + 2];
                    data[i + 2] = b;
                }
                break;
            default:
                return null;
        }
        BufferedImage image2 = new BufferedImage(cols, rows, type);
        image2.getRaster().setDataElements(0, 0, cols, rows, data);
        return image2;
    }
    /**
     * Mat类型转为BufferedImage
     * @param mat
     * @return
     */
    public static BufferedImage toBufferedImage(Mat mat){
        OpenCVFrameConverter.ToOrgOpenCvCoreMat converter = new OpenCVFrameConverter.ToOrgOpenCvCoreMat();
        Frame frame = converter.convert(mat);
        BufferedImage bufferedImage = new Java2DFrameConverter().getBufferedImage(frame);
        return bufferedImage;
    }
}
